#include "stdafx.h"
#include "SubItemsSearcher.h"

#include "TaskManager.h"
#include <chrono>
#include <thread>
#include "Item.h"
#include "ItemBrowser.h"
#include "Constants.h"
#include <QMetaType>
#include "TCpu.h"
#include "HelperFunctions.h"

SubItemsSearcher::SubItemsSearcher(TaskManager *ts)
    : Task(Constants::strings.searchSubItemsTaskName, ts), manager(ts)
{

}

SubItemsSearcher::~SubItemsSearcher()
{

}

void SubItemsSearcher::start()
{
    _finished = false;

    auto cpu = TCpu::instance();

    // basic
    cpu->setOn(this->channel(), Constants::strings.itemsFound, this, &SubItemsSearcher::itemsFound);
    cpu->setOn(this->channel(), Constants::strings.searchResultShown, this, &SubItemsSearcher::searchResultShown);
    cpu->setOn(this->channel(), Constants::strings.mainItemFound, this, &SubItemsSearcher::mainItemFound);
    cpu->setOn(this->channel(), Constants::strings.compareItemSelected, this, &SubItemsSearcher::compareItemSelected);


    session()->send(Constants::strings.searchSubItems, QVariantMap{{"link", this->link}});
    playSound(Constants::audioPath.browseFirstSubItem);
}

void SubItemsSearcher::itemsFound(QVariantMap arg)
{
    for (const auto &p : arg)
    {
        if (!isSearchFinished())
        {
            manager->subItemBrowsedNumber++;

            auto item = Item::fromVariantMap(p.toMap());
            // #TODO : browse item;
            auto browser = new ItemBrowser(manager);

            // #TODO : set configs for item browser
            browser->setItem(item);
            browser->setConfigure(manager->subBrowserConfig);
            browser->setSupportKeyword(manager->supportKeyword);

            browser->start();
            switch (manager->subItemBrowsedNumber - 1)
            {
            case 0:
                playSound(Constants::audioPath.browseFirstSubItem);
                break;
            case 1:
                playSound(Constants::audioPath.browseSecondSubItem);
                break;
            case 2:
                playSound(Constants::audioPath.browseThirdSubItem);
            default:
                ;
            }
            browser->waitForFinished();
        }
    }
    _finished = true;
}

bool SubItemsSearcher::isSearchFinished()
{
    return !manager->subBrowserConfig.enabled || manager->subItemBrowsedNumber >= manager->subBrowserConfig.number;
}

void SubItemsSearcher::searchResultShown(QVariantMap arg)
{
    session()->send(Constants::strings.lookupItem, { {"secondsPerScreen", this->manager->scrollInterval} });
}

void SubItemsSearcher::mainItemFound(QVariantMap arg)
{

}

void SubItemsSearcher::compareItemSelected(QVariantMap arg)
{

}

void SubItemsSearcher::waitForFinished()
{
    std::chrono::milliseconds span(10);
    while (!_finished)
        std::this_thread::sleep_for(span);
}
